'''

see http://paste.pocoo.org/show/98040/

'''

import objc
objc.setVerbose(1)

def myKeyCGEventCallback(proxy, type, event, refcon):
    print 'key', (proxy, type, event, refcon)
    #sys.exit(0)
    return event
    
import Quartz

# Create an event tap for key events.

#eventMask = (1 << Quartz.kCGEventKeyUp);
eventMask = Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp);
print "event mask:", eventMask

eventTap = Quartz.CGEventTapCreate(
               #Quartz.kCGHIDEventTap, 
               Quartz.kCGSessionEventTap,
               #Quartz.kCGAnnotatedSessionEventTap,
               
               Quartz.kCGHeadInsertEventTap,
               #Quartz.kCGHeadInsertEventTap,

               #Quartz.kCGEventTapOptionDefault,
               Quartz.kCGEventTapOptionListenOnly,

               eventMask,

               myKeyCGEventCallback,

               #None
           )
print "event tap created"

if not eventTap:
    print "failed to create key event tap"
    sys.exit(1);
print "key event taped"

# Create a run loop source.
runLoopSource = Quartz.CFMachPortCreateRunLoopSource(
                    Quartz.kCFAllocatorDefault,
                    eventTap, 0
                )

# Add to the current run loop.
Quartz.CFRunLoopAddSource(
    Quartz.CFRunLoopGetCurrent(),
    runLoopSource,
    Quartz.kCFRunLoopCommonModes
)

# Enable the event tap.
Quartz.CGEventTapEnable(eventTap, True)

# Set it all running.
Quartz.CFRunLoopRun()

# release tap
eventTap.CFRelease()
